<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="10">
          <!-- 搜索框 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsersList">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域，主要是后两列使用了作用域插槽-->
      <el-table :data="userslist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="tel" label="电话"></el-table-column>
        <el-table-column label="状态">
          <template v-slot:default="slotinfo">
            <!-- {{ slotinfo.row }} -->
            <el-switch v-model="slotinfo.row.role_status"
              active-color="#13ce66" inactive-color="#ded9df"
              @change="userStateChanged(slotinfo.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template v-slot:default="slotinfo">
            <!-- {{ slotinfo.row }} -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(slotinfo.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(slotinfo.row.id)"></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top-end" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 用户添加 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="closeDialog">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="addForm.tel"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="closeEditDialog">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="tel">
          <el-input v-model="editForm.tel"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserinfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getInfo, postInfo } from '@/utils/http'
export default {
  data () {
    // 表单自定义验证手机号
    var checkTel = (rule, value, callback) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[5-7])[0-9]{8}$/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的7~11位的电话'))
    }
    return {
      // 获取用户列表参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userslist: [],
      total: 0,
      // 用户对话框显示否
      addDialogVisible: false,
      addForm: { username: '', password: '', tel: 123 },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 20, message: '长度5~20！', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 20, message: '长度3~20，包含字母、数字、下划线', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkTel, trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      // 查询到的用户对象
      editForm: {},
      editFormRules: {
        tel: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkTel, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUsersList()
  },
  methods: {
    async getUsersList () {
      // const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      const { data: res } = await getInfo('users', { params: this.queryInfo })
      if (res.status !== '200') return this.$message.error('查询角色列表失败!')
      this.userslist = res.data.users
      this.total = res.data.total
    },
    // 监听 pagesize 改变
    handleSizeChange (newsize) {
      this.queryInfo.pagesize = newsize
      this.getUsersList()
    },
    // 监听 pagenum 改变
    handleCurrentChange (newpage) {
      this.queryInfo.pagenum = newpage
      this.getUsersList()
    },
    // 监听 switch 状态的改变
    async userStateChanged (info) {
      // console.log(info)
      const obj = {
        id: info.id,
        role_status: info.role_status
      }
      // const { data: res } = await this.$http.get('userstate', { params: obj })
      const { data: res } = await getInfo('userstate', { params: obj })
      if (res.status !== '200') {
        info.role_status = !info.role_status
        return this.$message.error('修改失败')
      }
      this.$message.success('成功！')
    },
    closeDialog () {
      this.$refs.addFormRef.resetFields()
    },
    closeEditDialog () {
      this.$refs.editFormRef.resetFields()
    },
    // 提交用户信息时候最后进行一下预校验
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await postInfo('adduser', this.addForm)
        if (res.status !== '200') return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getUsersList()
      })
    },
    async showEditDialog (id) {
      const { data: res } = await getInfo(`fetch?id=${id}`)
      this.editForm = res.data
      this.editDialogVisible = true
    },
    editUserinfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return false
        // const { data: res } = await this.$http.get('edit', { params: this.editForm })
        const { data: res } = await getInfo('edit', { params: this.editForm })
        this.editForm = res.data
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新列表
        this.getUsersList()
        // 提示用户
        this.$message.success('修改成功!')
      })
    },
    // 根据id删除用户信息
    async removeUserById (id) {
      const confirmResult = await this.$messageBox.confirm('此操作会永远删除这个用户，确定继续吗？', '警告', {
        confirmButtonText: '是的',
        cancelButtonText: '不是',
        type: 'warning'
      }).catch(err => err)
      // 1、用户确认，输出字符串 'confirm'
      // 2、用户取消，需要捕捉错误然后返回出去，输出'cancel'
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消')
      }
      console.log(id)
      const { data: res } = await getInfo('/deluser', { params: { id } })
      if (res.status !== '200') return this.$message.error('删除失败')
      this.$message.success('删除成功!')
      this.getUsersList()
    }
  }
}
</script>

<style>
</style>
